package com.cqs.learning.java;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * @Author lixw
 * @Date 5/22/20 8:59 AM
 */
public class Producer extends Observable {
    List<Observer> listener = new ArrayList<>();
    public Producer() {
        //注册监听者
        listener.add(new Consumer());
    }

    //发布更新 --- 广播消费给注册到Producer的消费者
    public void  publishEvent(){
        System.out.println("生产者有更新，通知消费者");
        Producer producer = this;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Observer observer : listener) {
            observer.update(producer, LocalDateTime.now().format(formatter) + "发送新的消息");
        }

    }

    public static void main(String[] args) {
        new Producer().publishEvent();
    }

    //定义消费者 也就是监听者
    class Consumer implements Observer {
        //定义接收到消息的逻辑
        @Override
        public void update(Observable o, Object arg) {
            System.out.println("消费者接受到" + o + "的消息:" + arg);
        }
    }
}
